package cn.b.sky.mes.andon.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import cn.b.sky.mes.andon.dao.MessageRuleAndonAssignDao;
import cn.b.sky.mes.andon.dao.MessageRuleDao;
import cn.b.sky.mes.andon.dao.MessageRuleItemDao;
import cn.b.sky.mes.andon.model.MessageRule;
import cn.b.sky.mes.andon.model.MessageRuleAndonAssign;
import cn.b.sky.mes.andon.model.MessageRuleItem;
import cn.b.sky.mes.andon.model.condition.MessageRuleAndonAssignCondition;
import cn.b.sky.mes.andon.model.condition.MessageRuleCondition;
import cn.b.sky.mes.andon.model.condition.MessageRuleItemCondition;
import cn.b.sky.mes.andon.service.MessageRuleService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.Page;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;

/**
 * 
 * <strong>Title : MessageRuleServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.mes.andon.service.impl<br></strong>
 * <strong>Description : </strong>消息规则操作业务类实现<br> 
 * <strong>Create on : 2016-10-17 下午02:49:27<br></strong>
 * <p>
 * @author JunLin.Yang<br>
 * @version <strong>v1.0.0</strong>
 */
@Service("messageRuleService")
public class MessageRuleServiceImpl implements MessageRuleService {

  private static final Logger LOGGER = LoggerFactory.getLogger(MessageRuleServiceImpl.class);

  @Resource
  private MessageRuleDao messageRuleDao;

  @Resource
  private MessageRuleItemDao messageRuleItemDao;

  @Resource
  private MessageRuleAndonAssignDao messageRuleAndonAssignDao;

  @Override
  public int insertMessageRule(MessageRule data) {
    if (null == data) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.insertMessageRule(data);
  }

  @Override
  public int updateMessageRule(MessageRule data) {
    if (null == data) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.updateMessageRule(data);
  }

  @Override
  public BatchJobReport deleteMessageRule(MessageRule data) {
    if (null == data) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.deleteMessageRuleByPrimaryKey(data.getSiteCode(), data.getRuleCode());
  }

  @Override
  public long getMessageRulesCount() {
    return this.messageRuleDao.getMessageRulesCount();
  }

  @Override
  public List<MessageRule> selectMessageRules() {
    return this.messageRuleDao.selectMessageRules();
  }

  @Override
  public BatchJobReport deleteMessageRuleByPrimaryKey(String siteCode, String ruleCode) {
    String cause = "";
    Boolean success = true;
    try {
      this.messageRuleDao.deleteMessageRuleByPrimaryKey(siteCode, ruleCode);
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(ruleCode, cause, success);
  }

  @Override
  public MessageRule getMessageRuleByPrimaryKey(String siteCode, String ruleCode) {
    return this.messageRuleDao.getMessageRuleByPrimaryKey(siteCode, ruleCode);
  }

  @Override
  public boolean existMessageRuleByPrimaryKey(String siteCode, String ruleCode) {
    return this.messageRuleDao.existMessageRuleByPrimaryKey(siteCode, ruleCode);
  }

  @Override
  public boolean existsMessageRuleByCondition(MessageRuleCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.existsMessageRuleByCondition(condition);
  }

  @Override
  public MessageRule getMessageRuleByCondition(MessageRuleCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.getMessageRuleByCondition(condition);
  }

  @Override
  public List<MessageRule> selectMessageRulesByCondition(MessageRuleCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.selectMessageRulesByCondition(condition);
  }

  @Override
  public List<MessageRule> selectMessageRulePageDataByCondition(MessageRuleCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.selectMessageRulePageDataByCondition(condition);
  }

  @Override
  public Page selectMessageRulePageByCondition(MessageRuleCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    condition.setData(this.messageRuleDao.selectMessageRuleWithAssociatedInfoPageDataByCondition(condition));
    condition.setTotalCount(this.messageRuleDao.getMessageRulesCountByCondition(condition));
    return condition;
  }

  @Override
  public long getMessageRulesCountByCondition(MessageRuleCondition condition) {
    if (null == condition) {
      throw ImeException.newException(SystemConstant.PARAMETERNULL);
    }
    return this.messageRuleDao.getMessageRulesCountByCondition(condition);
  }

  @Override
  public void insertMessageRulesWithAssociatedData(MessageRule messageRule) {

    messageRule.preProcessingToStore();
    this.messageRuleDao.insertMessageRule(messageRule);
    if (!CollectionUtils.isEmpty(messageRule.getMessageRuleItemList())) {
      for (MessageRuleItem messageRuleItem : messageRule.getMessageRuleItemList()) {
        if (StringUtils.isNotBlank(messageRuleItem.getTimerStartEcode())
            && StringUtils.isNotBlank(messageRuleItem.getMessageCode()) && null != messageRuleItem.getTimeInterval()) {
          messageRuleItem.setSiteCode(messageRule.getSiteCode());
          messageRuleItem.setRuleCode(messageRule.getRuleCode());
          this.messageRuleItemDao.insertMessageRuleItem(messageRuleItem);
        }
      }
    }

    if (0 == messageRule.getAllAndonsFlag() && !CollectionUtils.isEmpty(messageRule.getMessageRuleAndonAssignList())) {
      for (MessageRuleAndonAssign messageRuleAndonAssign : messageRule.getMessageRuleAndonAssignList()) {
        if (StringUtils.isNotBlank(messageRuleAndonAssign.getAndonCode())
            && StringUtils.isNotBlank(messageRuleAndonAssign.getWorkUnitCode())) {
          messageRuleAndonAssign.setSiteCode(messageRule.getSiteCode());
          messageRuleAndonAssign.setRuleCode(messageRule.getRuleCode());
          this.messageRuleAndonAssignDao.insertMessageRuleAndonAssign(messageRuleAndonAssign);
        }
      }
    }

  }

  @Override
  public void updateMessageRulesWithAssociatedData(MessageRule messageRule) {

    this.messageRuleDao.updateMessageRule(messageRule);
    if (!CollectionUtils.isEmpty(messageRule.getMessageRuleItemList())) {
      for (MessageRuleItem messageRuleItem : messageRule.getMessageRuleItemList()) {
        if (messageRuleItem.isDelete()) {
          this.messageRuleItemDao.deleteMessageRuleItemByPrimaryKey(messageRuleItem.getId());
        } else if (null == messageRuleItem.getId()) {
          if (StringUtils.isNotBlank(messageRuleItem.getTimerStartEcode())
              && StringUtils.isNotBlank(messageRuleItem.getMessageCode())
              && null != messageRuleItem.getTimeInterval()) {
            messageRuleItem.setSiteCode(messageRule.getSiteCode());
            messageRuleItem.setRuleCode(messageRule.getRuleCode());
            this.messageRuleItemDao.insertMessageRuleItem(messageRuleItem);
          }
        }
      }
    }

    //先清空所有的暗灯关联信息再新增
    MessageRuleAndonAssignCondition messageRuleAndonAssignCondition = new MessageRuleAndonAssignCondition();
    messageRuleAndonAssignCondition.setSiteCode(messageRule.getSiteCode());
    messageRuleAndonAssignCondition.setRuleCode(messageRule.getRuleCode());
    this.messageRuleAndonAssignDao.deleteMessageRuleAndonAssignByCondition(messageRuleAndonAssignCondition);

    if (0 == messageRule.getAllAndonsFlag() && !CollectionUtils.isEmpty(messageRule.getMessageRuleAndonAssignList())) {
      for (MessageRuleAndonAssign messageRuleAndonAssign : messageRule.getMessageRuleAndonAssignList()) {
        if (StringUtils.isNotBlank(messageRuleAndonAssign.getAndonCode())
            && StringUtils.isNotBlank(messageRuleAndonAssign.getWorkUnitCode())) {
          messageRuleAndonAssign.setSiteCode(messageRule.getSiteCode());
          messageRuleAndonAssign.setRuleCode(messageRule.getRuleCode());
          this.messageRuleAndonAssignDao.insertMessageRuleAndonAssign(messageRuleAndonAssign);
        }
      }
    }
  }

  @Override
  public BatchJobReport deleteMessageRulesWithAssociatedData(String siteCode, String ruleCode) {
    String cause = "";
    Boolean success = true;
    try {
      this.messageRuleDao.deleteMessageRuleByPrimaryKey(siteCode, ruleCode);

      MessageRuleItemCondition messageRuleItemCondition = new MessageRuleItemCondition();
      messageRuleItemCondition.setSiteCode(siteCode);
      messageRuleItemCondition.setRuleCode(ruleCode);
      this.messageRuleItemDao.deleteMessageRuleItemByCondition(messageRuleItemCondition);

      MessageRuleAndonAssignCondition messageRuleAndonAssignCondition = new MessageRuleAndonAssignCondition();
      messageRuleAndonAssignCondition.setSiteCode(siteCode);
      messageRuleAndonAssignCondition.setRuleCode(ruleCode);
      this.messageRuleAndonAssignDao.deleteMessageRuleAndonAssignByCondition(messageRuleAndonAssignCondition);
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport(ruleCode, cause, success);
  }

  @Override
  public MessageRule getMessageRulesWithAssociatedData(String siteCode, String ruleCode) {
    MessageRule messageRule = this.messageRuleDao.getMessageRuleByPrimaryKey(siteCode, ruleCode);
    MessageRuleItemCondition messageRuleItemCondition = new MessageRuleItemCondition();
    messageRuleItemCondition.setSiteCode(siteCode);
    messageRuleItemCondition.setRuleCode(ruleCode);
    messageRule.setMessageRuleItemList(
        this.messageRuleItemDao.selectMessageRuleItemsDetailByCondition(messageRuleItemCondition));

    MessageRuleAndonAssignCondition messageRuleAndonAssignCondition = new MessageRuleAndonAssignCondition();
    messageRuleAndonAssignCondition.setSiteCode(siteCode);
    messageRuleAndonAssignCondition.setRuleCode(ruleCode);
    messageRule.setMessageRuleAndonAssignList(
        this.messageRuleAndonAssignDao.selectMessageRuleAndonAssignsDetailByCondition(messageRuleAndonAssignCondition));

    return messageRule;
  }

}
